package com.dmall.directed.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class GraphBFS {
    private Graph G;
    private boolean[] visited;
    private ArrayList<Integer> order = new ArrayList<>();

    public GraphBFS(Graph G) {
        this.G = G;
        visited = new boolean[G.V()];

        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                bfs(i);
            }
        }
    }

    private void bfs(int v) {
        visited[v] = true;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            order.add(cur);
            for (Integer w : G.adj(cur)) {
                if (!visited[w]) {
                    visited[w] = true;
                    queue.add(w);
                }
            }
        }
    }

    public Iterable<Integer> order() {
        return order;
    }

    public static void main(String[] args) {
        String filename = GraphBFS.class.getClassLoader().getResource("com/dmall/directed/graph/ug.txt").getPath();
        Graph g = new Graph(filename, true);
        GraphBFS graphBFS = new GraphBFS(g);
        System.out.println("BFS Order: " + graphBFS.order());
    }
}
